// ==UserScript==
// @name         三角洲HIT地图样式
// @namespace    http://tampermonkey.net/
// @version      1.9
// @description  为HIT地图添加三角洲行动战术风格，并优化标记显示，支持文本替换为图片
// @author       FreeFalling_Snow
// @match        *://map.hit.edu.cn/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    console.log('三角洲脚本开始执行');

    let iframeDoc = null;
    let isProcessing = false;
    let dragTimeout = null; // 将dragTimeout提升到全局作用域

    // 定义文本到图片URL的映射字典
    const textToImageMap = {

        '西大直街校门': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/cgcld.png',
        '长征一号运载火箭': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/hjcld.png',
        '快舟一号甲运载火箭': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/hjcld.png',
        '明德楼西侧出入口': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/ffcld.png',
        '明德楼西侧出入口': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/ffcld.png',
        '和兴路校门': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/tjcld.png',
        '西苑出入口': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/sjcld.png',
        '西大直街复华街车辆出口': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/sjcld.png',
        '西门': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/sjcld.png',
        '护军街园丁8号楼行人通道': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/tjcld.png',
        '嵩山路行人通道': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/tjcld.png',
        '科学园北门': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/tjcld.png',
        '复兴街行人通道': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/tjcld.png',
        '科学园2A行人通道': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/tjcld.png',
        '科学园2H行人通道': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/tjcld.png',
        '淮河路行人通道': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/tjcld.png',
        '校外街出入口': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/cgcld.png',
        '西配楼': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/dtwz.png',
        '泵房': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/dtwz.png',
        '电力部': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/dtwz.png',
        '公厕': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/dtcld.png',
        '黄河路校门': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/dtcld.png',
        'A20公寓': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/boss.png',
        '主楼': 'https://game.gtimg.cn/images/dfm/cp/a20240729directory/img/lv3/boss.png',
        '正心楼': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2rxoxX_OQ_tOo1qcepHgwlBkD5LIFwACNisAArySMFZEhH5bm-vw6DYE.png',
        '诚意楼': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2rxoxX_OQ_tOo1qcepHgwlBkD5LIFwACNisAArySMFZEhH5bm-vw6DYE.png',
        '科技创新大厦': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2rxoxX_OQ_tOo1qcepHgwlBkD5LIFwACNisAArySMFZEhH5bm-vw6DYE.png',
        '文体中心': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2rxoxX_OQ_tOo1qcepHgwlBkD5LIFwACNisAArySMFZEhH5bm-vw6DYE.png',
        '图书馆': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2rtoxX_OjIkuLcOHuqlcM9Eov4_nLgACNSsAArySMFaFd8i_awAB07I2BA.png',
        'B2栋': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2rtoxX_OjIkuLcOHuqlcM9Eov4_nLgACNSsAArySMFaFd8i_awAB07I2BA.png',
        '体育场': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2r1oxX_OZ8AfuixfiDkk4E3dSwiXZgACNysAArySMFawLmLNT5PJdTYE.png',
        '航天馆': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2r1oxX_OZ8AfuixfiDkk4E3dSwiXZgACNysAArySMFawLmLNT5PJdTYE.png',
        '风雨操场': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2rpoxX_OTinV2O3CiBzUwOmeYsT4NgACNCsAArySMFa3GYFOQ1RfSjYE.png',
        '逸夫楼': 'https://img.remit.ee/api/file/BQACAgUAAyEGAASHRsPbAAEB2rpoxX_OTinV2O3CiBzUwOmeYsT4NgACNCsAArySMFa3GYFOQ1RfSjYE.png',
        // 可以继续添加更多映射
    };

    // 应用三角洲样式到地图
    function applyDeltaStyle() {
        try {
            const iframe = document.getElementById('IfrMap');
            if (!iframe) {
                console.log('未找到IfrMap iframe');
                return false;
            }

            // 等待iframe完全加载
            iframe.addEventListener('load', function() {
                // 使用重试机制处理动态内容
                let retryCount = 0;
                const maxRetries = 5;
                const retryInterval = 300;

                function checkAndProcessLy2() {
                    try {
                        iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
                        const ly2 = iframeDoc.getElementById('ly2');

                        if (ly2) {
                            console.log('找到ly2元素，应用三角洲样式');
                            // 直接设置内联样式确保生效
                            ly2.style.filter = 'grayscale(20%) contrast(150%) saturate(20%) brightness(80%)';

                            // 处理标记元素
                            processAllMarkers();

                            // 添加地图交互监听
                            setupMapInteractionListeners();

                            // 创建新的遮罩
                            createMapMask();

                            return true; // 成功找到并处理
                        } else if (retryCount < maxRetries) {
                            console.log(`未找到ly2元素，第${retryCount + 1}次重试...`);
                            retryCount++;
                            setTimeout(checkAndProcessLy2, retryInterval);
                            return false;
                        } else {
                            console.log('未找到ly2元素，已达到最大重试次数');
                            // 即使没有ly2也继续执行其他操作
                            processAllMarkers();
                            setupMapInteractionListeners();
                            createMapMask();
                            return false;
                        }
                    } catch (e) {
                        console.log('访问iframe内容时出错:', e);
                        if (retryCount < maxRetries) {
                            retryCount++;
                            setTimeout(checkAndProcessLy2, retryInterval);
                        }
                        return false;
                    }
                }

                function createMapMask() {
                    const mapMask = document.createElement('div');
                    mapMask.id = 'delta-map-mask';
                    mapMask.style.position = 'fixed';
                    mapMask.style.top = iframe.getBoundingClientRect().top + 'px';
                    mapMask.style.left = iframe.getBoundingClientRect().left + 'px';
                    mapMask.style.width = iframe.offsetWidth + 'px';
                    mapMask.style.height = iframe.offsetHeight + 'px';
                    mapMask.style.backgroundImage = 'url("https://game.gtimg.cn/images/dfm/cp/a20240729directory/map_mask.png")';
                    mapMask.style.backgroundSize = 'cover';
                    mapMask.style.backgroundRepeat = 'no-repeat';
                    mapMask.style.pointerEvents = 'none';
                    mapMask.style.zIndex = '9999';
                    // 将遮罩添加到body而不是iframe内部
                    document.body.appendChild(mapMask);
                }

                // 开始检查
                checkAndProcessLy2();
            });





            return true;
        } catch (e) {
            console.log('应用样式时出错:', e);
            return false;
        }
    }

    // 处理所有标记元素
    function processAllMarkers() {
        if (!iframeDoc || isProcessing) return;

        isProcessing = true;
        console.log('开始处理所有标记元素');

        // 处理地点元素
        processLocationMarkers(iframeDoc);

        isProcessing = false;
    }

    // 处理地点元素
    function processLocationMarkers(doc) {
        // 查找所有id为"g7"的元素
        const locationElements = doc.querySelectorAll('#g7');

        if (locationElements.length > 0) {
            console.log(`找到 ${locationElements.length} 个地点元素`);

            locationElements.forEach(location => {
                // 如果已经处理过，跳过
                if (location.getAttribute('data-delta-processed') === 'true') {
                    return;
                }

                // 获取地点名称
                const locationName = location.querySelector('nobr')?.textContent || '地点';

                if (locationName) {
                    console.log('处理地点:', locationName);

                    // 配置偏移量（可以根据需要调整）
                    const offsetConfig = {
                        left: -10,
                        top: 10
                    };

                    // 保存原始位置和z-index
                    const originalLeft = location.style.left;
                    const originalTop = location.style.top;
                    const originalZIndex = location.style.zIndex;
                    const originalPosition = location.style.position;

                    // 解析原始位置值
                    const leftValue = parseInt(originalLeft) || 0;
                    const topValue = parseInt(originalTop) || 0;

                    // 创建新的简化地点标记
                    const newLocation = document.createElement('div');
                    newLocation.id = location.id;

                    // 应用偏移量
                    newLocation.style.left = (leftValue + offsetConfig.left) + 'px';
                    newLocation.style.top = (topValue + offsetConfig.top) + 'px';

                    newLocation.style.zIndex = originalZIndex;
                    newLocation.style.position = originalPosition;
                    newLocation.setAttribute('data-delta-processed', 'true');

                    // 检查是否有对应的图片
                    const imageUrl = textToImageMap[locationName];

                    if (imageUrl) {
                        // 创建图片元素
                        const imgElement = document.createElement('img');
                        imgElement.src = imageUrl;
                        imgElement.alt = locationName;
                        imgElement.style.width = '28px'; // 根据需要调整大小
                        imgElement.style.height = '28px';
                        imgElement.style.display = 'block';
                        imgElement.style.margin = '0 auto';

                        // 添加图片到新地点标记
                        newLocation.appendChild(imgElement);

                        // 可选：添加文字说明（如果需要）
                        const textSpan = document.createElement('span');
                        textSpan.textContent = locationName;
                        textSpan.style.font = '12x "Helvetica Neue", Arial, Helvetica, sans-serif';
                        textSpan.style.whiteSpace = 'nowrap';
                        textSpan.style.color = '#FFFFFF';
                        textSpan.style.display = 'block';
                        textSpan.style.textAlign = 'center';
                        textSpan.style.marginTop = '2px';
                        textSpan.style.fontWeight = 'bold'; // 添加加粗效果
                        newLocation.appendChild(textSpan);
                    } else {
                        // 没有对应图片，只显示白色文字
                        const textSpan = document.createElement('span');
                        const locationList =['暖廊','工大附中','专家楼','贵新','西苑','栋']
                        // 使用 some() 方法检查列表中是否有字符串包含 locationName
                        const containsLocation = locationList.some(location =>
                                                                   locationName.includes(location)
                                                                  );

                        if(!containsLocation){
                            textSpan.textContent = locationName;
                        }else{
                            textSpan.textContent = '';
                        }

                        textSpan.style.font = '12px "Helvetica Neue", Arial, Helvetica, sans-serif';
                        textSpan.style.whiteSpace = 'nowrap';
                        textSpan.style.color = '#FFFFFF';
                        textSpan.style.display = 'block';
                        textSpan.style.fontWeight = 'bold'; // 添加加粗效果

                        newLocation.appendChild(textSpan);
                    }

                    // 替换原始地点标记
                    location.parentNode.replaceChild(newLocation, location);
                }
            });
        } else {
            console.log('未找到地点元素');
        }
    }

    // 设置地图交互监听器
    function setupMapInteractionListeners() {
        if (!iframeDoc) return;

        // 监听鼠标拖动事件
        const mapContainer = iframeDoc.getElementById('ly2') || iframeDoc.body;
        if (mapContainer) {
            let isDragging = false;

            // 鼠标按下事件
            mapContainer.addEventListener('mousedown', function() {
                isDragging = true;
            });

            // 鼠标释放事件
            mapContainer.addEventListener('mouseup', function() {
                isDragging = false;
                // 延迟处理，确保地图已完成更新
                if (dragTimeout) clearTimeout(dragTimeout);
                dragTimeout = setTimeout(() => {
                    processAllMarkers();
                }, 300);
            });

            // 鼠标移动事件（拖动中）
            mapContainer.addEventListener('mousemove', function() {
                if (isDragging) {
                    // 拖动中清除之前的超时
                    if (dragTimeout) clearTimeout(dragTimeout);
                }
            });

            // 滚轮事件
            mapContainer.addEventListener('wheel', function(e) {
                // 延迟处理，确保地图已完成更新
                if (dragTimeout) clearTimeout(dragTimeout);
                dragTimeout = setTimeout(() => {
                    processAllMarkers();
                }, 300);
            }, { passive: true });

            console.log('已设置地图交互监听器');
        }

        // 设置观察器监听DOM变化（作为备用方案）
        const observer = new MutationObserver(function(mutations) {
            // 检查是否有新的标记元素被添加
            let shouldProcess = false;
            for (const mutation of mutations) {
                if (mutation.addedNodes && mutation.addedNodes.length > 0) {
                    shouldProcess = true;
                    break;
                }
            }

            if (shouldProcess) {
                // 延迟处理，避免频繁触发
                if (dragTimeout) clearTimeout(dragTimeout);
                dragTimeout = setTimeout(() => {
                    processAllMarkers();
                }, 300);
            }
        });

        observer.observe(iframeDoc.body, {
            childList: true,
            subtree: true
        });
    }

    // 主执行函数
    function main() {
        console.log('开始应用三角洲样式');

        // 立即尝试
        if (applyDeltaStyle()) {
            return;
        }

        // 如果立即失败，监听DOM变化
        const observer = new MutationObserver(function() {
            if (applyDeltaStyle()) {
                observer.disconnect();
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    // 启动脚本
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', main);
    } else {
        main();
    }
})();
